//
//  Request.swift
//  whetherDemo
//
//  Created by 姚东 on 2025/2/19.
//

import Foundation

let baseUrl = "https://api.open-meteo.com/v1/"
class NetworkManager {
    
    static let shared = NetworkManager()
    
    private init() {}
    
    // 封装 GET 请求，并返回解码后的 JSON 数据
    func getRequest<T: Decodable>(urlString: String, responseType: T.Type, completion: @escaping (Result<T, Error>) -> Void) {
        guard let url = URL(string:baseUrl + urlString) else {
            completion(.failure(NSError(domain: "Invalid URL", code: 400, userInfo: nil)))
            return
        }
        
        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        
        let session = URLSession.shared
        
        let task = session.dataTask(with: request) { data, response, error in
            if let error = error {
                completion(.failure(error))
                return
            }
            
            guard let data = data else {
                completion(.failure(NSError(domain: "No data", code: 404, userInfo: nil)))
                return
            }
            
            do {
                let decoder = JSONDecoder()
                let decodedResponse = try decoder.decode(T.self, from: data)
                completion(.success(decodedResponse))
            } catch {
                completion(.failure(error))
            }
        }
        
        task.resume()
    }
}
